package com.strato.mvc.enhance.defaults.v1_0_0.interceptor;

import java.lang.ref.WeakReference;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.osgi.framework.BundleContext;

import com.strato.annotation.base.v1_0_0.lifecycle.BundleContextAware;
import com.strato.annotation.osgi.v1_0_0.service.OsgiService;
import com.strato.base.osgi.v1_0_0.BundleUtil;
import com.strato.mvc.api.v1_0_0.control.HttpInvoker;
import com.strato.mvc.api.v1_0_0.control.HttpInvokerInterceptor;
import com.strato.mvc.api.v1_0_0.control.PathVariableCollector;
import com.strato.mvc.api.v1_0_0.model.ModelAndView;
import com.strato.mvc.api.v1_0_0.user.UserContext;
import com.strato.mvc.api.v1_0_0.util.RequestMeta;
import com.strato.mvc.security.v1_0_0.api.AuthorityService;

@OsgiService
public class MvcCommonInterceptor implements HttpInvokerInterceptor,BundleContextAware {

	private WeakReference<BundleContext> context;

	@Override
	public int getOrder() {
		return 99;
	}

	@Override
	public boolean canHandle(HttpServletRequest request, HttpServletResponse response, PathVariableCollector pvc, RequestMeta meta, HttpInvoker invoker) {
		if(context.get()!=null){
			AuthorityService checker=BundleUtil.getCachedService(context.get(), AuthorityService.class, null);
			request.setAttribute("authorityService", checker);
		}
		request.setAttribute("sysuser", UserContext.getUser());
		request.setAttribute("sysuserId", UserContext.get());
		return true;
	}
	
	@Override
	public boolean beforeInvocation(HttpServletRequest request, HttpServletResponse response, PathVariableCollector pvc, ModelAndView mav,HttpInvoker invoker) {
		return true;
	}

	@Override
	public void invocationSuccess(HttpServletRequest request, HttpServletResponse response, PathVariableCollector pvc, ModelAndView mav, HttpInvoker invoker) {
	}

	@Override
	public void invokeFinally(HttpServletRequest request, HttpServletResponse response, PathVariableCollector pvc, HttpInvoker invoker) {
	}

	@Override
	public void invocationFailed(HttpServletRequest request, HttpServletResponse response, PathVariableCollector pvc, Exception e, HttpInvoker invoker) {
	}

	@Override
	public void setBundleContext(WeakReference<BundleContext> context) {
		this.context=context;
	}

}
